package 网络编程.课后作业;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 6）、基于TCP协议实现客户端上传图片文件到服务器，
 * 服务器保存图片的位置建议在当前项目工程的upload/images/文件夹中。
 * （通过字节流实现）
 */

/**
 * 服务器端
 */
public class M6 {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;
        //创建服务器端的ServerSocket对象
        serverSocket = new ServerSocket(8888);

        //获取Socket对象
        //2.获取Socket对象
        Socket s=serverSocket.accept();
        String ip=s.getInetAddress().getHostAddress();
        System.out.println(ip+"connected...");
//3.接收客户端传来的图片。源：Socket流
        InputStream in=s.getInputStream();

//4.存放到服务器端的硬盘。目的：硬盘
        File dir=new File("/Users/liuxiang/Documents/doc");
        if(!dir.exists()) dir.mkdirs();
        File file=new File(dir,ip+".jpg");
        FileOutputStream os=new FileOutputStream(file);
        byte [] bt=new byte[1024];
        int len;
        while((len=in.read(bt))!=-1)
        {
            os.write(bt, 0, len);
        }

//5.告诉客户端上传成功。目的：Socket流
        OutputStream out=s.getOutputStream();
        out.write("上传成功".getBytes());


//关闭资源
        in.close();
        s.close();
        serverSocket.close();
    }
}


/**
 * 客户端
 */
class HocTs {
    public static void main(String[] args) throws IOException {

        //创建客户端Socket对象
        Socket s = new Socket("172.20.10.2", 8888);

        //读取要上传的图片
        InputStream is = new FileInputStream("/Users/liuxiang/Documents/AB2CD8C332ABE5C573A18FE788E6A1B3.jpg");

        //3将图片发送到服务器端，目的Socket流
        OutputStream out = s.getOutputStream();
        byte[] bt = new byte[1024];
        int len = 0;
        while ((len = is.read(bt)) != -1) {
            out.write(bt, 0, len);
        }
        s.shutdownOutput();
        //4.接收服务器端返回的数据。源：Socket流
        InputStream isIn = s.getInputStream();
        byte[] btIn = new byte[1024];
        int lenIn = isIn.read(btIn);
        String text = new String(btIn, 0, lenIn);
        System.out.println(text);



//关闭资源
        is.close();
        s.close();
    }
}
